const config = require('./config')
const Redis=require("ioredis")

//创建Redis客户端实例
const RedisCli = new Redis({
    host: config.redis_host,
    port: config.redis_port,
    password: config.redis_passwd
});

//监听错误信息
RedisCli.on("error",function(err){
    console.log("Redis Cli connect err:",err.message);
    RedisCli.quit();
});

/**
 * 根据key获取value
 * @param {*} key
 * @returns 
 */
async function GetRedis(key) {
    try{
        const result = await RedisCli.get(key)
        if(result == null)
        {
            console.log('result:','<'+result+'>','key not found');
            return null;
        }
        console.log('result','<'+result+'>','Get Key Success');
        return result
    }catch(err)
    {
        console.log('GetRedis Err',err);
        return null;
    }
}

/**
 * 根据key查询redis是否存在
 * @param {*} key
 * @returns
 */
async function QueryRedis(key) {
    try{
        const result =await RedisCli.exists(key);
        if(result==null)
        {
            console.log('result:','<'+result+'>','key is null');
            return null
        }
        console.log('result:','<'+result+'>','key exists');
        return result;
    }catch(err)
    {
        console.log("QueryRedis Err",err);
        return null
    }
}

/**
 * 设置key与value，以及expire时间
 * @param {*} key
 * @param {*} value
 * @param {*} exptime
 * @returns
 */
async function  SetRedisExpire(key,value,exptime) {
    try{
        console.log(`Connected to Redis DB ${config.redis_host}`,config.redis_port); 
        //设置键和值
        await RedisCli.set(key,value);
        await RedisCli.expire(key,exptime);
        console.log(`Set [${key}] with TTL: ${exptime}s`);
        return true;

    }catch(err)
    {
        console.log("SetRedisExpire Err",err);
        return null
    }
}

/**
 * 退出函数
 */

function Quit(){
    RedisCli.quit();
}

module.exports = {GetRedis,QueryRedis,Quit,SetRedisExpire}